<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName">
          <!-- 角色管理 -->
          <el-tab-pane label="角色管理" name="role">
            <el-button
              style="margin-bottom: 16px;"
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="dialogVisible = true"
            >
              新增角色
            </el-button>
            <el-table
              :data="roleList"
              style="width: 100%"
              border
              stripe
            >
              <el-table-column
                label="序号"
                type="index"
                width="100"
                align="center"
                :index="indexMethod"
              />
              <el-table-column
                label="角色名"
                prop="name"
                header-align="center"
              />
              <el-table-column
                label="描述"
                prop="description"
                header-align="center"
              />
              <el-table-column
                label="操作"
                align="center"
                width="200"
              >
                <template v-slot="{ row }">
                  <el-button type="text" @click="showAssign(row.id)">分配权限</el-button>
                  <el-button type="text" @click="edit(row)">修改</el-button>
                  <el-button type="text" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-row type="flex" justify="end" style="margin-top: 14px;">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="total"
                :page-size="pagesize"
                :current-page="page"
                @current-change="changeFn"
              />
            </el-row>
            <!-- 新增角色弹框 -->
            <el-dialog
              :title="title"
              :visible.sync="dialogVisible"
              width="40%"
              @closed="afterClose"
            >
              <el-form ref="form" v-loading="roleLoading" :model="form" label-width="80px" :rules="rules">
                <el-form-item label="角色名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                  <el-input v-model="form.description" placeholder="请输入角色描述" />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
              </template>
            </el-dialog>
            <!-- 分配权限弹框 -->
            <el-dialog title="分配权限" :visible.sync="showAssignDialog" @close="closeAssignDialog">
              <el-tree
                ref="tree"
                v-loading="treeLoading"
                :data="permissionList"
                :props="{ label: 'name' }"
                show-checkbox
                default-expand-all
                check-strictly
                node-key="id"
              />
              <template #footer>
                <div style="text-align: right;">
                  <el-button @click="showAssignDialog = false">取消</el-button>
                  <el-button type="primary" @click="assignPerm">确定</el-button>
                </div>
              </template>
            </el-dialog>
          </el-tab-pane>
          <!-- 公司信息 -->
          <el-tab-pane label="公司信息" name="company">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="warning"
              :closable="false"
              show-icon
            />
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width: 400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getRoleList, delRole, addRole, updateRole, getRoleDetail, getCompanyById, assignPermToRole } from '@/api/setting'
import { mapState } from 'vuex'
import { getPermissionList } from '@/api/permisson'
import { listToTree } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'role',
      roleList: [], // 角色列表
      total: 0, // 总数
      pagesize: 5, // 每页条数
      page: 1, // 第几页
      loading: false,
      roleLoading: false,
      dialogVisible: false,
      treeLoading: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称' }],
        description: [{ required: true, message: '请输入角色描述' }]
      },
      companyForm: {}, // 企业信息
      showAssignDialog: false,
      roleId: '', // 当前点击的角色id
      permissionList: [] // 所有权限列表
    }
  },
  computed: {
    // 个人信息, 其中包含企业id
    ...mapState('user', ['userInfo']),
    title() {
      return this.form.id ? '修改角色' : '新增角色'
    }
  },
  created() {
    this.getRoleList() // 获取角色列表
    this.getCompanyInfo() // 获取企业信息
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { rows, total } = await getRoleList(this.page, this.pagesize)
      this.roleList = rows
      this.total = total
      this.loading = false
    },
    // 获取企业信息
    async getCompanyInfo() {
      this.companyForm = await getCompanyById(this.userInfo.companyId)
    },
    changeFn(currentPage) {
      // 切换页码之后改变当前页
      this.page = currentPage
      // 获取对应页码数据
      this.getRoleList()
    },
    // 自定义表格显示序号
    indexMethod(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 删除角色
    async del(id) {
      try {
        await this.$confirm('此操作将删除该角色, 是否继续?', '提示', { type: 'warning' })
      } catch {
        return
      }
      // 删除
      await delRole(id)
      this.$message.success('删除成功')
      // 重新渲染
      // 如果当前页只有一条数据, 删除之后页码减1
      if (this.roleList.length === 1) this.page--
      this.getRoleList()
    },
    // 关闭角色弹框动画结束之后
    afterClose() {
      // 重置表单数据
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 添加/修改角色
    async addRole() {
      // 表单校验
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.form.id) {
        // 修改
        await updateRole(this.form)
      } else {
        // 添加
        await addRole(this.form)
        // 将page改为最后一页
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
      }
      this.dialogVisible = false
      this.$message.success('操作成功')
      // 重新渲染
      this.getRoleList()
    },
    // 修改角色按钮
    async edit(row) {
      this.roleLoading = true
      // 回显
      this.dialogVisible = true
      this.form = await getRoleDetail(row.id)
      // this.form = { ...row }
      this.roleLoading = false
    },
    // 分配权限按钮 回显
    async showAssign(id) {
      this.treeLoading = true
      this.roleId = id
      this.showAssignDialog = true
      // 显示全部权限
      const data = await getPermissionList()
      this.permissionList = listToTree(data, '0')
      // 回显当前点击角色权限
      const { permIds } = await getRoleDetail(id)
      this.$refs.tree.setCheckedKeys(permIds)
      this.treeLoading = false
    },
    closeAssignDialog() {
      // 关闭分配权限弹框时清空回显
      this.$refs.tree.setCheckedKeys([])
    },
    // 给角色分配权限
    async assignPerm() {
      await assignPermToRole({
        id: this.roleId,
        permIds: this.$refs.tree.getCheckedKeys() // 通过树形组件key方法获取选中
      })
      this.$message.success('分配权限成功')
      this.showAssignDialog = false
    }
  }
}
</script>

<style>

</style>
